package com.example.aopdemo.aop.aspect;


import com.example.aopdemo.aop.RecordOperationLog;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;

/**
 * @author luo
 * @since 2022/12/12 16:52
 */

@Aspect
@Slf4j
@Component
public class OrderOperationLogAspect {

    @Pointcut("@annotation(recordOperationLog)")
    public void orderOperationLogAnnotation(RecordOperationLog recordOperationLog) {
    }

    @Before(value = "orderOperationLogAnnotation(recordOperationLog)", argNames = "joinPoint,recordOperationLog")
    public void beforeOrderOperation(JoinPoint joinPoint, RecordOperationLog recordOperationLog) {


        Object arg = joinPoint.getArgs()[recordOperationLog.argumentIndex()];
        Field field = null;
        try {
            field = arg.getClass().getDeclaredField(recordOperationLog.orderIdName());
            field.setAccessible(true);
            Long orderId = (Long) field.get(arg);
            log.info("正在对订单id = {} 做记录 {}", orderId, arg);
        } catch (NoSuchFieldException | IllegalAccessException e) {
            e.printStackTrace();

        }
    }
}
